/*  GMooc - A Java web application for delivering massive open online courses
*   Copyright (C) 2012 Charles A. Wight
*   
*    This program is free software: you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation, either version 3 of the License, or
*   (at your option) any later version.
*
*   This program is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details.
*
*   You should have received a copy of the GNU General Public License
*   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package org.gmooc;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;

@SuppressWarnings("serial")
public class Profile extends HttpServlet {
	
	Objectify ofy = new DAO().ofy();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		User user = (User)request.getSession(true).getAttribute("User");
		if (user==null) user = ofy.find(User.class,UserServiceFactory.getUserService().getCurrentUser().getUserId());
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		String userRequest = request.getParameter("UserRequest");
		if ("Modify".equals(userRequest) || user.needsNewTermsAgreement()) out.println(profileForm(user));
		else out.println(profilePage(user));
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException {
		User user = (User)request.getSession(true).getAttribute("User");
		if (user==null) user = ofy.find(User.class,UserServiceFactory.getUserService().getCurrentUser().getUserId());
		
		if ("Cancel".equals(request.getParameter("UserRequest"))) {
			if (user.needsNewTermsAgreement()) request.getSession().invalidate();
			response.sendRedirect("/");
			return;
		}
		
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		if ("Update My Profile".equals(request.getParameter("UserRequest"))) {
			updateUser(user,request);
			request.getSession().setAttribute("User",user);
		}
		out.println(profilePage(user));
	}
	
	private String profileForm(User user) {
		
		StringBuffer buf = new StringBuffer(Home.header(user));
		if (user.isDeactivated()) buf.append("Your account has been deactivated. For additional information, cantact <a href=mailto:admin@gmooc.org>admin@gmooc.org</a>");
		else {
			buf.append("<h2>User Profile</h2>"
					+ "<table>"
					+ "<form method=post action=profile>"
					+ "<tr><td style='text-align:right'>First Name:</td><td><input type=text name=FirstName value='" + user.getFirstName() + "'></td></tr>"
					+ "<tr><td style='text-align:right'>Last Name:</td><td><input type=text name=LastName value='" + user.getLastName() + "'></td></tr>"
					+ "<tr><td style='text-align:right'><input type=checkbox name=MakeAnonymous value=true" + (user.isAnonymous()?" CHECKED":"") + "></td><td>Make me anonymous to other users (optional).</td></tr>"
					+ "<tr><td style='text-align:right'>Email:</td><td>" + user.getEmail() + "</td></tr>"
					+ "<tr><td style='text-align:right'><input type=checkbox id=checkbox1 name=TermsAgreed value=true onChange=checkButton();" + (user.needsNewTermsAgreement()?"></td><td style='color:red'>":" CHECKED></td><td>") + "I agree to the <a href=/about#terms>Gmooc Terms and Conditions of Use</a>.</td></tr>"
					+ "<tr><td></td><td><input id=button1 type=submit name=UserRequest value='Update My Profile'><input type=submit name=UserRequest value=Cancel></td></tr>"
					+ "</form>"
					+ "</table>");
			buf.append("<SCRIPT>function checkButton(){document.getElementById('button1').disabled=(document.getElementById('checkbox1').checked?'':'disabled')}checkButton()</SCRIPT>");
			if (user.needsNewTermsAgreement()) buf.append(About.terms);
		}
		return buf.toString() + Home.footer;		
	}
	
	private void updateUser (User user,HttpServletRequest request) {
		user.setFirstName(request.getParameter("FirstName"));
		user.setLastName(request.getParameter("LastName"));
		boolean anonymous = Boolean.parseBoolean(request.getParameter("MakeAnonymous")); // user preference
		if (user.getFullName().isEmpty()) anonymous = true;
		user.setAnonymous(anonymous);
		if (Boolean.parseBoolean(request.getParameter("TermsAgreed"))) {
			user.setTermsAgreedTo();
			if (user.getRoles()==0) user.activate();
		}
		ofy.put(user);
	}
	
	private String profilePage(User user) {
		StringBuffer buf = new StringBuffer(Home.header(user));
		if (user.isDeactivated()) buf.append("Your account has been deactivated. For additional information, cantact <a href=mailto:admin@gmooc.org>admin@gmooc.org</a>");
		else {
			buf.append("<h2>User Profile</h2>"
					+ new Date() + "<p>"
					+ "<table>"
					+ "<form method=get action=profile>"
					+ "<tr><td style='text-align:right;vertical-align:top'>Full Name:</td><td>" + user.getFullName() 
					+ (user.isAnonymous()?"<br>Your class discussion posts will list you as <i>Anonymous</i>":"")
					+ "</td></tr>"
					+ "<tr><td style='text-align:right'>Email:</td><td>" + user.getEmail() + "</td></tr>"
					+ "<tr><td style='text-align:right'>Role:</td><td>" + user.getPrincipalRole() + "</td></tr>"
					+ (user.getTermsAgreedTo().after(new Date(0))?"<tr><td></td><td>You agreed to the <a href=/about#terms>Gmooc Terms and Conditions of Use</a> on " + user.getTermsAgreedTo() + ".</td></tr>":"")
					+ "<tr><td></td><td><input type=submit name=UserRequest value='Modify'></td></tr>"
					+ "</form>"
					+ "</table>");
		}
		return buf.toString() + Home.footer;
	}
}
